package com.sdx.console.customer.web;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.console.service.OrgConsoleService;
import com.ibeetl.admin.console.service.UserConsoleService;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.BaseEntity;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.service.CustomerRoleService;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.AuthorizedBaesController;
import com.ibeetl.admin.core.web.JsonResult;
import com.sdx.common.entity.DictBusiness;
import com.sdx.common.utils.EDateUtil;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.common.utils.Utils;
import com.sdx.console.common.OperType;
import com.sdx.console.common.entity.BaseProvince;
import com.ibeetl.admin.core.service.RedisService;
import com.sdx.console.common.service.BaseDataService;
import com.sdx.console.common.service.CommonService;
import com.sdx.console.contract.entity.RightCustomerRole;
import com.sdx.console.customer.entity.ChoiceScore;
import com.sdx.console.customer.entity.CustomerInfo;
import com.sdx.console.customer.entity.RightCustomerProvince;
import com.sdx.console.customer.entity.UserOperationLog;
import com.sdx.console.customer.service.CustomerInfoService;
import com.sdx.console.entity.CustomerAccount;
import com.sdx.console.ncode.entity.RightRole;
import com.sdx.console.person.entity.CustomerExtInfo;
import com.sdx.console.person.service.CustomerExtInfoService;
import com.sdx.console.rightRole.entity.RightRoleFunction;
import com.sdx.console.system.entity.ChannelSet;
import com.sdx.console.system.service.ChannelSetService;
import com.sdx.console.system.service.DictBusinessService;
import com.sdx.console.utils.SmsUtils;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;
import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 会员管理 接口
 */
@RequestMapping("/customer/customerInfo")
@Controller
public class CustomerInfoController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(CustomerInfoController.class);
    private static final String MODEL = "/customer/customerInfo";
    private static final String MODEL_MEMBER = "/customer/member";
	private static final Integer TEACHER_ROLE = 2;
	private static final String RIGHT = "customer.right";
	private static final String SQL = "customer.customerInfo";

	@Resource
	private BaseDataService baseDataService;

    @Resource
	private CustomerInfoService customerInfoService;

    @Resource
    private DictBusinessService dictBusinessService;

	@Resource
	private ChannelSetService channelSetService;

	@Resource
	private OrgConsoleService orgConsoleService;

	@Resource
	private UserConsoleService userConsoleService;

	@Resource
	private CustomerExtInfoService customerExtInfoService;

	@Resource
	private CustomerRoleService customerRoleService;

	@Resource
	private CommonService commonService;

	@Resource
	private SQLManager sqlManager;

	@Resource
	private RedisService redisService;

	@Value("${sdx.loginPath}")
	private String loginPath;

	@Value("${sdx.h5loginPath}")
	private String h5loginPath;


	/**
	 * 初始化页面需要的列表数据，
	 * @param view 业务模块，来源渠道
	 */
	private void setPageParam(ModelAndView view) {
		List<DictBusiness> moduleList = dictBusinessService.getModule();
		view.addObject("moduleList",moduleList);
		List<ChannelSet> channelList = channelSetService.all();
		view.addObject("channelList",channelList);
		view.addObject("orgList",orgConsoleService.getOrgs());
		view.addObject("provinceList",baseDataService.getAllProvince());
		view.addObject("provList",baseDataService.getProvinces());
		view.addObject("roleList",customerRoleService.roleList());
    }


    /* 页面 */

    @GetMapping("/index.do")
    @Function("customer.customerInfo.query")
    @ResponseBody
    public ModelAndView index() {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view);
        return view;
    }

    public void load(String customerId,ModelAndView view,Integer tenantId) {
		CustomerInfo customerInfo = new CustomerInfo();
		customerInfo.setCustomerId(customerId);
		customerInfo.setTenantId(tenantId);
		PageQuery page = customerInfo.getPageQuery();
		customerInfoService.queryByCondition(page);
		customerInfo =(CustomerInfo) page.getList().get(0);
		List<String> ids = new ArrayList<>();
		ids.add(customerId);
		String json = customerInfoService.customersRole(ids);
		if (!StringUtils.isEmpty(json)) {
			JSONObject jsonObject = JSON.parseObject(json);
			String rolesName = jsonObject.getString(customerInfo.getCustomerId());
			customerInfo.set("rolesName", rolesName);
		}
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if(customerInfo.getRegisterTime()!=null){
			customerInfo.set("registerTimeStr", df.format(customerInfo.getRegisterTime()));
		}
	    DictBusiness db = dictBusinessService.queryById(customerInfo.getModule());
	    ChannelSet channelSet = new ChannelSet();
		channelSet.setChannelCode(customerInfo.getChannel());
		channelSet.setTenantId(tenantId);
	    ChannelSet cs = sqlManager.single(ChannelSet.class,channelSet);
	    //    queryById(customerInfo.getChannel());
	    if(db!=null){
			customerInfo.setModuleName(db.getDictValue());
		}
	    if(cs!=null){
			customerInfo.setChannelName(cs.getChannelName());
		}
	    view.addObject("customerInfo", customerInfo);
	    setPageParam(view);
	    try {
			if(customerInfo.getIsTeacher()==1){
				CustomerExtInfo customerExtInfo = customerExtInfoService.queryById(customerInfo.getCustomerId());
				view.addObject("customerExtInfo", customerExtInfo);
			}
		    view.addObject("customerInfoJson", JacksonUtils.toJsonString(customerInfo,JacksonUtils.DF1));
	    } catch (JsonProcessingException e) {
		    e.printStackTrace();
	    }
		view.addObject("courseGroups", sqlManager.select(SQL+".selectCourseGroup",BaseEntity.class));



    }

    @GetMapping("/edit.do")
    @Function("customer.customerInfo.edit")
    @ResponseBody
    public ModelAndView edit(String customerId,Integer tenantId) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
		load(customerId,view,tenantId);
        return view;
    }

	@GetMapping("/view.do")
	@Function("customer.customerInfo.view")
	@ResponseBody
	public ModelAndView view(String customerId,Integer tenantId) {
		ModelAndView view = new ModelAndView(MODEL+"/view.html");
		load(customerId,view,tenantId);
		return view;
	}

	@RequestMapping("/roleList.json")
	@Function("customer.customerInfo.view")
	@ResponseBody
	public JsonResult<List<BaseEntity>> roleList(String customerId) {
		//包含的权限
//		RightCustomerRole param = new RightCustomerRole();
//		param.setCustomerId(customerId);
//		//param.setOnceOnly(0);
//		List<RightCustomerRole> roleList = sqlManager.template(RightCustomerRole.class,param,"create_time desc");
		List<BaseEntity> roleList = customerRoleService.roleList(customerId);
		return JsonResult.success(roleList);
	}

    @GetMapping("/add.do")
    @Function("customer.customerInfo.add")
    @ResponseBody
    public ModelAndView add() {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        return view;
    }

	/**
	 * 设置为员工
	 * @return
	 */
	@GetMapping("/emp.do")
	@Function("customer.customerInfo.emp")
	@ResponseBody
	public ModelAndView emp(String customerId,Integer tenantId) {
		ModelAndView view = new ModelAndView(MODEL+"/emp.html");
		List<CoreUser> userList = userConsoleService.selectValidUser();
		view.addObject("userList",userList);
		load(customerId,view,tenantId);
		return view;
	}
    /* ajax json */

    @PostMapping("/list.json")
    @Function("customer.customerInfo.query")
    @ResponseBody
    public JsonResult<PageQuery> list(CustomerInfo condtion,HttpServletRequest request,String majorTypes)
    {
    	CoreUser user = getLoginUser(request);
		condtion.setTenantId(user.getTenantId());
		if(StringUtils.isNotEmpty(majorTypes)){
			if("1".equals(majorTypes)||"2".equals(majorTypes)){
				condtion.setMajorType(Integer.parseInt(majorTypes));
			}else{
				condtion.setCourseGroup(majorTypes);
			}
		}
        PageQuery page = condtion.getPageQuery();
        page.setOrderBy("updated_time desc,customer_id");
        customerInfoService.queryByCondition(page);
        List list = page.getList();
        List<String> ids = new ArrayList<>();
	    for (int i = 0; i < list.size(); i++) {
		    CustomerInfo customerInfo = (CustomerInfo)list.get(i);
		    ids.add(customerInfo.getCustomerId());
	    }
	    if (ids.size()>0) {
		    String json = customerInfoService.customersRole(ids);
		    if (!StringUtils.isEmpty(json)) {
			    JSONObject jsonObject = JSON.parseObject(json);
			    for (int i = 0; i < list.size(); i++) {
				    CustomerInfo customerInfo = (CustomerInfo) list.get(i);
				    String rolesName = jsonObject.getString(customerInfo.getCustomerId());
				    customerInfo.set("rolesName", rolesName);
			    }
		    }
	    }
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,CustomerInfo customerInfo,HttpServletRequest request) {
    	JsonResult result = JsonResult.success();

		CoreUser user = getLoginUser(request);

    	if (isNew) {
			customerInfoService.save(customerInfo);
		} else {
    		if(customerInfo.getMajorType()==null||customerInfo.getMajorType()!=3){
				customerInfo.setCourseGroupId(null);
			}
			customerInfo.setUpdatedBy(user.getId().intValue());
			customerInfo.setUpdatedName(user.getName());
			customerInfo.setUpdatedTime(new Date());
			customerInfoService.updateTemplate(customerInfo);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("customer.customerInfo.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)CustomerInfo customerInfo,HttpServletRequest request
							,@RequestParam("workPicurlFile") MultipartFile workPicurlFile
							,@RequestParam("dailyPicurlFile") MultipartFile dailyPicurlFile

		)
    {

        return save(true,customerInfo,request);
    }

    @PostMapping("/update.json")
    @Function("customer.customerInfo.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  CustomerInfo customerInfo,HttpServletRequest request

		) {
		return save(false,customerInfo,request);
    }

	@PostMapping("/emp.json")
	@Function("customer.customerInfo.emp")
	@ResponseBody
	public JsonResult<String> emp(String customerId,Integer userId,HttpServletRequest request) {

		JsonResult result = JsonResult.success();
		CoreUser user = getLoginUser(request);
		customerInfoService.saveEmp(user,customerId,userId);
		return result;
	}

	@RequestMapping("/grantCustomer.do")
	@Function("customer.customerInfo.grant")
	@ResponseBody
	public ModelAndView grantCustomer(String customerId,HttpServletRequest request) {
		ModelAndView view = new ModelAndView(MODEL+"/grantCustomer.html");
		view.addObject("customerId",customerId);
		CoreUser user = getLoginUser(request);
		RightRole rightRole = new RightRole();
		//个人角色
		rightRole.setRoleType(1);
		rightRole.setTenantId(user.getTenantId());
		List<RightRole> roleList = sqlManager.template(rightRole);
		view.addObject("roleList",roleList);
		Calendar cal = Calendar.getInstance();
		int year = cal.get(Calendar.YEAR);
		if (cal.get(Calendar.MONTH)>8) {
			year++;
		}
		view.addObject("year",year);
		return view;
	}


	@PostMapping("/grantCustomer.json")
	@Function("customer.customerInfo.grant")
	@ResponseBody
	public JsonResult<String> grantCustomer(String customerId,Integer choiceYear,Integer roleId,HttpServletRequest request) throws ParseException {
		JsonResult result = JsonResult.success();
		CoreUser user = getLoginUser(request);
		RightCustomerRole rightCustomerRole = new RightCustomerRole();
		rightCustomerRole.setCustomerId(customerId);
		rightCustomerRole.setRoleId(roleId);
		rightCustomerRole.setRightStatus(1);
		rightCustomerRole.setTenantId(user.getTenantId());
		rightCustomerRole.setRemark(user.getId()+" 授权！");
		rightCustomerRole.setLinkId(user.getId().toString());
		rightCustomerRole.setOnceOnly(0);
		rightCustomerRole.setRightSource(100);
		rightCustomerRole.setCreateTime(new Date());
		rightCustomerRole.setExpiredDate(EDateUtil.parseDateYMDHMS(choiceYear+"-08-31 23:59:59"));
		sqlManager.insertTemplate(rightCustomerRole);
		return result;
	}

	@PostMapping("/revokeCustomer.json")
	@Function("customer.customerInfo.grant")
	@ResponseBody
	public JsonResult<String> revokeCustomer(String customerId,Integer rightId,HttpServletRequest request) {
		JsonResult result = JsonResult.success();
		CoreUser user = getLoginUser(request);
		RightCustomerRole rightCustomerRole = new RightCustomerRole();
		rightCustomerRole.setRightId(rightId);
		rightCustomerRole.setRightStatus(0);
		sqlManager.updateTemplateById(rightCustomerRole);
		commonService.operLog(customerId, OperType.GK_MODIFY.getOperTypeId(),user.getId().intValue(),user.getName(),"收回权限，id="+rightId);
		return result;
	}

	public static void main(String[] args) {
		Calendar cal = Calendar.getInstance();
		System.out.println(cal.get(Calendar.YEAR));
	}
	@RequestMapping("/grant.do")
	@Function("customer.customerInfo.grant")
	@ResponseBody
	public ModelAndView grantPage(String customerId,HttpServletRequest request) {
		ModelAndView view = new ModelAndView(MODEL+"/grant.html");
		List<BaseProvince> provinceList = baseDataService.getValidProvinces();
		view.addObject("provinceList",provinceList);
		view.addObject("customerId",customerId);
		CoreUser user = getLoginUser(request);
		Map<String,Object> param = new HashMap<>();
		param.put("customerId",customerId);
		param.put("tenantId",user.getTenantId());
		List<BaseEntity> roleList = sqlManager.select(RIGHT+".orgRoles",BaseEntity.class,param);
		view.addObject("roleList",roleList);
		boolean rightFlag = false;
		for (BaseEntity item:roleList) {
			if (((Number)item.get("rightFlag")).intValue()==1) {
				rightFlag = true;
				break;
			}
		}
		view.addObject("rightFlag",rightFlag);
		RightCustomerProvince customerProvince = sqlManager.single(RightCustomerProvince.class,customerId);
		if (customerProvince!=null && !StringUtils.isEmpty(customerProvince.getProvinces())) {
			String provinces = ","+customerProvince.getProvinces()+",";
			for (BaseProvince baseProvince:provinceList) {
				int provFlag = 0;
				if (provinces.indexOf(","+baseProvince.getProvId()+",")>-1) {
					provFlag = 1;
				}
				baseProvince.set("provFlag",provFlag);
			}
		}
		return view;
	}

	@PostMapping("/grant.json")
	@Function("customer.customerInfo.grant")
	@ResponseBody
	public JsonResult<String> grant(String customerId,String[] provIds,Integer roleId,
									String expiredDate,Integer validityDay,HttpServletRequest request) {
		JsonResult result = JsonResult.success();
		CoreUser user = getLoginUser(request);
		//判断是否需要授权省份
		RightRoleFunction roleFunction = new RightRoleFunction();
		roleFunction.setTenantId(user.getTenantId());
		//修改省份权限
		roleFunction.setFunctionId(1);
		roleFunction.setRoleId(roleId);
		if (sqlManager.templateCount(roleFunction)>0) {
			String provinceIds = String.join(",",provIds);
			RightCustomerProvince customerProvince = new RightCustomerProvince();
			customerProvince.setCustomerId(customerId);
			customerProvince.setUpdatedBy(user.getId().intValue());
			customerProvince.setUpdatedName(user.getName());
			customerProvince.setUpdatedTime(new Date());
			customerProvince.setProvinces(provinceIds);
			if (sqlManager.updateTemplateById(customerProvince)==0) {
				customerProvince.setCreatedBy(user.getId().intValue());
				customerProvince.setCreatedName(user.getName());
				customerProvince.setCreatedTime(new Date());
				sqlManager.insertTemplate(customerProvince);
			}
		}
		Date date = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			if(StringUtils.isNotEmpty(expiredDate)){
				date = sdf.parse(expiredDate);
			}else if(validityDay!=null){
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(new Date());
				calendar.add(Calendar.DAY_OF_MONTH, validityDay);//增加days天
				date = calendar.getTime();
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		RightCustomerRole customerRole = null;
		Map<String,Object> param = new HashMap<>();
		param.put("customerId",customerId);
		param.put("tenantId",user.getTenantId());
		customerRole = sqlManager.selectSingle(RIGHT+".getRole",param,RightCustomerRole.class);
		if (customerRole!=null && customerRole.getRoleId().intValue()!=roleId.intValue()) {
			//更改roleid
			Integer rightId = customerRole.getRightId();
			customerRole = new RightCustomerRole();
			customerRole.setRightId(rightId);
			customerRole.setRoleId(roleId);
			if(date!=null){
				customerRole.setExpiredDate(date);
			}
			sqlManager.updateTemplateById(customerRole);
		} else if (customerRole==null) {
			//新增授权
			customerRole = new RightCustomerRole();
			customerRole.setCustomerId(customerId);
			customerRole.setTenantId(user.getTenantId());
			customerRole.setCreateTime(new Date());
			customerRole.setLinkId(user.getId().toString());
			customerRole.setRightSource(100);
			customerRole.setOnceOnly(0);
			if(date!=null){
				customerRole.setExpiredDate(date);
			}
			customerRole.setRoleId(roleId);
			customerRole.setRightStatus(1);
			sqlManager.insertTemplate(customerRole);
		}


		return result;
	}

	@PostMapping("/revoke.json")
	@Function("customer.customerInfo.grant")
	@ResponseBody
	public JsonResult<String> revoke(String customerId,HttpServletRequest request) {
		JsonResult result = JsonResult.success();
		CoreUser user = getLoginUser(request);
		String remark = "操作员："+user.getId()+" 于"+ EDateUtil.getNowDateStr()+"收回咨询师授权";
		customerInfoService.revokeRole(customerId,remark);
		return result;
	}

    @GetMapping("/view.json")
    @Function("customer.customerInfo.query")
    @ResponseBody
    public JsonResult<CustomerInfo>queryInfo(String customerId) {
        CustomerInfo customerInfo = customerInfoService.queryById( customerId);
        return  JsonResult.success(customerInfo);
    }

    @PostMapping("/delete.json")
    @Function("customer.customerInfo..del")
    @ResponseBody
    public JsonResult delete(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        //List<Long> idList = ConvertUtil.str2longs(ids);
		List<String> idList = new ArrayList<String>();
		Collections.addAll(idList,ids.split(","));
        customerInfoService.batchDelCustomerInfo(idList);
        return JsonResult.success();
    }

	@PostMapping("/teacher.json")
	@Function("customer.customerInfo.teacher")
	@ResponseBody
	public JsonResult teacher(String ids,HttpServletRequest request) {
		CoreUser user = getLoginUser(request);
		List<String> idList = Utils.strToList(ids,",");
		for (int i = 0; i < idList.size(); i++) {
			customerInfoService.setTearch(idList.get(i),user.getId().intValue(),user.getName());
		}
		return JsonResult.success();
	}


	@GetMapping("/indexTeacher.do")
	@ResponseBody
	public ModelAndView teacherindex() {
		ModelAndView view = new ModelAndView("/person/customerExtInfo/teacher.html") ;
		setPageParam(view);
		return view;
	}


	@PostMapping("/listCustomer.json")
	@ResponseBody
	public JsonResult<PageQuery> listCustomer(CustomerInfo condtion)
	{
		PageQuery page = condtion.getPageQuery();
		page.setOrderBy("updated_time desc,customer_id");
		customerInfoService.queryByConditionCustomer(page);
		return JsonResult.success(page);
	}

	/**
	 * 修改高考信息
	 * @return
	 */
	@GetMapping("/exam.do")
	@Function("customer.customerInfo.exam")
	@ResponseBody
	public ModelAndView exam(String customerId) {
		ModelAndView view = new ModelAndView(MODEL+"/exam.html");
//		ModelAndView view = new ModelAndView(MODEL+"/infoEdit.html");
		CustomerInfo customerInfo = customerInfoService.queryById(customerId);
		ChoiceScore choiceScore = customerInfoService.queryChoiceScore(customerId,customerInfo.getChoiceYear(),customerInfo.getMajorType(),customerInfo.getProvinceId());
		if(choiceScore!=null){
			customerInfo.setScoreId(choiceScore.getScoreId());
			customerInfo.setScore(choiceScore.getScore());
			customerInfo.setRank(choiceScore.getRank());
			customerInfo.setCourseGroupId(choiceScore.getCourseGroupId());
			customerInfo.setValueGroup(choiceScore.getValueGroup());
			customerInfo.setSubjectFirst(choiceScore.getSubjectFirst());
			customerInfo.setSubjectFirstLevel(choiceScore.getSubjectFirstLevel());
			customerInfo.setSubjectSecond(choiceScore.getSubjectSecond());
			customerInfo.setSubjectSecondLevel(choiceScore.getSubjectSecondLevel());
			customerInfo.setIsConfirmed(choiceScore.getIsConfirmed());
		}
		view.addObject("customerInfo", customerInfo);
		try {
			view.addObject("customerInfoJson", JacksonUtils.toJsonString(customerInfo,JacksonUtils.DF1));
		}catch (Exception e){
			e.printStackTrace();
		}
		List<BaseProvince> prov = baseDataService.getProv(1);
		view.addObject("provinceList",prov);
		return view;
	}

	@RequestMapping("/unlockScore.json")
	@Function("customer.customerInfo.exam")
	@ResponseBody
	public JsonResult<List<UserOperationLog>> unlockScore(String customerId,String scoreId,HttpServletRequest request) {
		CoreUser user = getLoginUser(request);
		ChoiceScore choiceScore = new ChoiceScore();
		choiceScore.setScoreId(scoreId);
		choiceScore.setIsConfirmed(0);
		sqlManager.updateTemplateById(choiceScore);
		String sql = "UPDATE coredb.customer_info SET unlock_count=unlock_count+1 WHERE customer_id=?";
		SQLReady sqlReady = new SQLReady(sql,customerId);
		sqlManager.executeUpdate(sqlReady);
		UserOperationLog log = new UserOperationLog();
		log.setCustomerId(customerId);
		log.setOperationType(1);
		log.setCreatedBy(user.getId().intValue());
		log.setCreatedName(user.getName());
		log.setCreatedTime(new Date());
		log.setOperationRemark("分数解锁");
		sqlManager.insertTemplate(log);
		return JsonResult.success();
	}

	@RequestMapping("/log.json")
	@Function("customer.customerInfo.exam")
	@ResponseBody
	public JsonResult<List<UserOperationLog>> log(String customerId) {
		//包含的权限
		UserOperationLog log = new UserOperationLog();
		log.setCustomerId(customerId);
		List<UserOperationLog> logList = sqlManager.template(UserOperationLog.class,log,"created_time desc");
		return JsonResult.success(logList);
	}

	@PostMapping("/exam.json")
	@Function("customer.customerInfo.exam")
	@ResponseBody
	public JsonResult<String> exam(CustomerInfo customerInfo,HttpServletRequest request) {

		JsonResult result = JsonResult.success();
		CoreUser user = getLoginUser(request);
		customerInfo.setUpdatedBy(user.getId().intValue());
		customerInfo.setUpdatedName(user.getName());
		customerInfo.setUpdatedTime(new Date());
		customerInfoService.updateTemplate(customerInfo);

		UserOperationLog log = new UserOperationLog();
		log.setCustomerId(customerInfo.getCustomerId());
		log.setOperationType(1);
		log.setCreatedBy(user.getId().intValue());
		log.setCreatedName(user.getName());
		log.setCreatedTime(new Date());
		log.setOperationRemark("高考省份年份修改");
		sqlManager.insertTemplate(log);



		return result;
	}



	@GetMapping("/getOrder.json")
	@ResponseBody
	public JsonResult getOrder(String customerId,Integer type) {
		JsonResult result = JsonResult.success();
		Map<String,Object> param = new HashMap<>();
		param.put("customerId",customerId);
//		List<BaseEntity> list = sqlManager.select(SQL + ".selectRightRole", BaseEntity.class, param);
		List<BaseEntity> list = sqlManager.select(SQL + ".selectOrder", BaseEntity.class, param);
		for (BaseEntity entity : list) {
			Integer majorTypeId = (Integer) entity.get("majorTypeId");
			Integer score = (Integer) entity.get("score");
			String provName =  entity.get("provName").toString();
			String orderName =  entity.get("orderName").toString();
			String majorTypeName = "";
			if(majorTypeId==1){
				majorTypeName = "文科";
			}else if(majorTypeId==2){
				majorTypeName = "理科";
			}else if(majorTypeId==3){
				majorTypeName =  entity.get("shortGroup").toString().replaceAll(",","");
			}
			String content = orderName+"("+provName+"  "+majorTypeName+"  "+score+"分)";
			entity.set("content",content);

			BigDecimal bignum = new BigDecimal(entity.get("totalMoney").toString());
			entity.set("totalMoney",bignum.divide(new BigDecimal("100"))+"元");
		}
		result.setData(list);
		return result;
	}


	@GetMapping("/info.do")
	@Function("customer.member.info")
	@ResponseBody
	public ModelAndView info(String customerId,Integer tenantId) {
		ModelAndView view = new ModelAndView(MODEL_MEMBER+"/info.html");
//		load(customerId,view,tenantId);
		CustomerInfo customerInfo = customerInfoService.queryById(customerId);
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if(customerInfo.getRegisterTime()!=null){
			customerInfo.set("registerTimeStr", df.format(customerInfo.getRegisterTime()));
		}
		view.addObject("customerInfo", customerInfo);

		return view;
	}

	@GetMapping("/infoEdit.do")
	@ResponseBody
	public ModelAndView infoEdit(String customerId,Integer tenantId) {
		ModelAndView view = new ModelAndView(MODEL_MEMBER+"/infoEdit.html");
		load(customerId,view,tenantId);
		return view;
	}

	@PostMapping("/getBaseData.json")
	@ResponseBody
	public JsonResult getBaseData(Integer provinceId) {
		JsonResult result = JsonResult.success();
		Map<String,Object> param = new HashMap<>();
		param.put("provinceId",provinceId);
		BaseEntity entity = sqlManager.selectSingle(SQL + ".selectBaseData", param, BaseEntity.class);
		result.setData(entity);
		return result;
	}

	@PostMapping("/saveInfo.json")
	@ResponseBody
	public JsonResult saveInfo(String customerId,Integer[] courseGroupId,Integer provinceId,Integer majorType,
							   Integer score,Integer rank,Integer choiceYear,Integer choiceMode,Integer tenantId,
							   HttpServletRequest request) {
		JsonResult result = JsonResult.success();
		CoreUser user = getLoginUser(request);
		//更新 用户信息
		CustomerInfo customerInfo = new CustomerInfo();
		customerInfo.setCustomerId(customerId);
		customerInfo.setTenantId(tenantId);
		int courseGroup = 0;
		for (Integer id : courseGroupId) {
			courseGroup += id;
		}
		if(choiceMode!=0){
			majorType = 3;
			customerInfo.setCourseGroupId(courseGroup);
		}
		customerInfo.setMajorType(majorType);
		customerInfo.setChoiceYear(choiceYear);
		customerInfo.setProvinceId(provinceId+"");
		customerInfo.setUpdatedBy(user.getId().intValue());
		customerInfo.setUpdatedName(user.getName());
		customerInfo.setUpdatedTime(new Date());
		customerInfoService.updateTemplate(customerInfo);

		ChoiceScore choiceScore = new ChoiceScore();
		choiceScore.setCustomerId(customerId);
		choiceScore.setYear(choiceYear);
		choiceScore.setProvinceId(provinceId);
		choiceScore.setMajorTypeId(majorType);
		choiceScore.setRank(rank);
		choiceScore.setScore(score);
		//判断分数是否存在
		ChoiceScore cScore = sqlManager.templateOne(choiceScore);
		choiceScore.setIsSelected("1");
		choiceScore.setIsConfirmed(1);
		if(majorType==3){
			choiceScore.setCourseGroupId(courseGroup);
		}
		sqlManager.update(SQL+".updateChoiceScore",choiceScore);
		if(cScore==null){
			choiceScore.setScoreId(Utils.uuid());
			choiceScore.setCreateTime(new Date());
			choiceScore.setHasShared("0");
			sqlManager.insertTemplate(choiceScore);
		}else{
			choiceScore.setScoreId(cScore.getScoreId());
			choiceScore.setIsSelected("1");
			choiceScore.setIsConfirmed(1);
			sqlManager.updateTemplateById(choiceScore);
		}
		return result;
	}


	@GetMapping("/memberIndex.do")
	@Function("customer.member.query")
	@ResponseBody
	public ModelAndView memberIndex(String customerId) {
		ModelAndView view = new ModelAndView(MODEL_MEMBER+"/index.html") ;
		setPageParam(view);
		view.addObject("customerId",customerId);
		return view;
	}

	@PostMapping("/memberList.json")
	@Function("customer.member.query")
	@ResponseBody
	public JsonResult<PageQuery> memberList(CustomerInfo condtion,HttpServletRequest request)
	{
		CoreUser user = getLoginUser(request);
		condtion.setTenantId(user.getTenantId());
		PageQuery page = condtion.getPageQuery();
		customerInfoService.queryEolByCondition(page);
		return JsonResult.success(page);
	}

	@GetMapping("/updateStatus.do")
	@Function("customer.member.status")
	@ResponseBody
	public ModelAndView updateStatus(String customerId) {
		ModelAndView view = new ModelAndView(MODEL_MEMBER+"/update.html");
		CustomerInfo customerInfo = customerInfoService.queryById(customerId);
		try {
			view.addObject("member", JacksonUtils.toJsonString(customerInfo,JacksonUtils.DF1));
		}catch (Exception e){

		}
		return view;
	}

	@PostMapping("/updateStatus.json")
	@ResponseBody
	public JsonResult updateStatus(CustomerInfo customerInfo,HttpServletRequest request) {
		JsonResult result = JsonResult.success();
		CoreUser user = getLoginUser(request);
		customerInfo.setUpdatedBy(user.getId().intValue());
		customerInfo.setUpdatedName(user.getName());
		customerInfo.setUpdatedTime(new Date());
		customerInfoService.updateTemplate(customerInfo);

		return result;
	}

	@PostMapping("/excel/import.do")
	@Function("customer.customerInfo.import")
	@ResponseBody
	public JsonResult importExcel(@RequestParam("file") MultipartFile file,HttpServletRequest request) throws Exception {
		CoreUser user = getLoginUser(request);
		if (file.isEmpty()) {
			return JsonResult.fail();
		}
		InputStream ins = file.getInputStream();
		//实例化实现了AnalysisEventListener接口的类
//		ExcelListener listener = new ExcelListener();
		//传入参数
//		ExcelReaderBuilder read = EasyExcel.read(ins);

		List<LinkedHashMap> list = EasyExcel.read(ins).sheet(0).doReadSync();
		String orderId = "6";
		for (LinkedHashMap tel : list) {
			String phone = tel.get(0).toString();
			CustomerAccount account = customerInfoService.inserCust(phone, user.getTenantId());
			if(account!=null && account.getCustomerId()!=null){
				customerInfoService.inserFinTrans(account.getCustomerId(),user.getTenantId(),orderId);
				Map param = new HashMap();
				param.put("userPhone",phone);
				param.put("bookId","6");
				SendSmsResponse response = SmsUtils.sendSms(phone,"SMS_206549848",param);
			}

		}
		ins.close();
		return JsonResult.success();
	}

	/**
	 * 模拟登陆获取参数
	 * @param customerId
	 * @param request
	 * @return
	 */
	@PostMapping("/login.json")
	@ResponseBody
	public JsonResult login(String customerId,HttpServletRequest request,Integer type) {
		JsonResult result = JsonResult.success();
		CoreUser user = getLoginUser(request);
		String customerToken = Utils.uuid();
		String key = "bshb_"+customerToken;
		redisService.setValue(key,customerId,5, TimeUnit.MINUTES);
		JSONObject json= new JSONObject();
		json.put("customerToken",customerToken);
		if(type!=null&&type==2){
			json.put("loginPath",h5loginPath);
		}else{
			json.put("loginPath",loginPath);
		}
		result.setData(json);
		commonService.operLog(customerId, OperType.CUSTOMER_LOGIN.getOperTypeId(),user.getId().intValue(),user.getName(),"模拟登陆");
		return result;
	}

	/**
	 * 收回热点精读权限
	 * @param ids
	 * @param request
	 * @return
	 */
	@PostMapping("/revokeRead.json")
	@Function("customer.customerInfo.revokeRead")
	@ResponseBody
	public JsonResult<String> revokeRead(String ids,HttpServletRequest request) {
		JsonResult result = JsonResult.success();
		List<String> idList = Utils.strToList(ids,",");
		CoreUser user = getLoginUser(request);
		String remark = "操作员："+user.getId()+" 于"+ EDateUtil.getNowDateStr()+"收回热点精读授权";
		customerInfoService.revokeRead(idList,remark);
		return result;
	}


	@PostMapping("/getScoreRank.json")
	@ResponseBody
	public JsonResult getScoreRank(Integer provinceId,Integer majorTypeId,Integer score) {
		JsonResult result = JsonResult.success();
		Map<String,Object> param = new HashMap<>();
		param.put("provinceId",provinceId);
		BaseEntity baseEntity = sqlManager.selectSingle(SQL + ".selectBaseData", param, BaseEntity.class);

		param.put("majorTypeId",majorTypeId);
		param.put("year",baseEntity.get("rankYear"));
		param.put("score",score);
		BaseEntity entity = sqlManager.selectSingle(SQL + ".queryScoreRank", param, BaseEntity.class);
		result.setData(entity);
		return result;
	}

}
